<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>商品</title>
    <link rel="stylesheet" href="layui/css/layui.css">
    <style>
        tbody .layui-table-cell{
            height:90px;
            line-height: 90px;
        }
    </style>
</head>
<body>
<div class="layui-container" style="padding-top: 30px;">

    <!--添加或修改商品弹出框-开始-->
    <div id="insertOrUpdateDiv" style="display: none;padding-top: 30px;">
        <form class="layui-form" lay-filter="dataFrm" id="dataFrm">
            <input type="hidden" name="id" class="layui-input">

            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">名称：</label>
                    <div class="layui-input-inline">
                        <input type="text" name="name" lay-verify="required|name" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">单价：</label>
                    <div class="layui-input-inline">
                        <input type="text" name="price" lay-verify="required|price" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">简介：</label>
                    <div class="layui-input-inline">
                        <textarea name="content" placeholder="40字数以内" lay-verify="required|content" class="layui-textarea"></textarea>
<!--                        <input type="text" name="content" lay-verify="required|content" autocomplete="off" class="layui-input">-->
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">分类：</label>
                    <div class="layui-input-inline">
                        <select name="typeId" lay-verify="required" lay-search="" id="typeIds">

                        </select>
                    </div>
                </div>

                <div class="layui-inline">
                    <label class="layui-form-label">图片：</label>
                    <div class="layui-input-block">
                        <button type="button" class="layui-btn layui-btn-radius" id="test1">选择图片</button>
                        <div id="editUploadBtn" style="display: none">
                            <button type="button" class="layui-btn layui-btn-normal layui-btn-radius" id="uploadBtn">点击上传</button>
                        </div>
                        <div class="layui-upload-list">
                            <img class="layui-upload-img" id="demo1" width="190px" height="130px" style="display: none">
                            <p id="demoText"></p>
                        </div>

                    </div>
                </div>

                <!-- 存放图片路径 -->
                <input type="hidden" name="picture" id="picture" lay-verify="picture|required" autocomplete="off" class="layui-input">
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="button" class="layui-btn" lay-submit="" lay-filter="submit">提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
    <!--添加或修改商品分类弹出框-结束-->

    <fieldset class="layui-elem-field layui-field-title">
        <legend>商品列表</legend>
    </fieldset>

    <form class="layui-form">
        <div class="demoTable">
            商品：
            <div class="layui-inline">
                <input class="layui-input" id="send_name" placeholder="输入关键字" autocomplete="off">
            </div>
            单价：
            <div class="layui-inline">
                <input class="layui-input" id="send_price" autocomplete="off">
            </div>
            分类：
            <div class="layui-input-inline">
                <select name="type" id="send_type" lay-search="">

                </select>
            </div>

            <button type="button" class="layui-btn" data-type="reload" id="do_search"><i class="layui-icon">&#xe615;</i>搜索</button>
        </div>
    </form>
    <table class="layui-hide" id="test" lay-filter="test"></table>

    <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-normal layui-btn-sm" lay-event="insert"><i class="layui-icon">&#xe654;</i>添加</button>
            <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="batchDelete"><i class="layui-icon">&#xe642;</i>删除</button>

        </div>
    </script>
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-normal layui-btn-sm" lay-event="update"><i class="layui-icon">&#xe642;</i>编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="delete"><i class="layui-icon">&#xe640;</i>删除</a>
    </script>

    <script src="layui/layui.js" charset="utf-8"></script>
    <script>
        layui.use(['table','jquery','form','upload'], function () {
            var table = layui.table;
            var $ = layui.jquery;
            var form = layui.form;
            var upload = layui.upload;
            var tableIns = table.render({
                elem: '#test'
                , url: '/goodsApi/goodsList'
                ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
                , title: '商品列表'
                , id: 'test'
                , cols: [
                    [
                        {type: 'checkbox', fixed: 'left'}
                        , {field: 'id',  title: '#', sort: true,width: 60}
                        , {field: 'name', title: '商品'}
                        , {field: 'picture', title: '图片',templet:img,width: 140}
                        , {field: 'price',  title: '单价',width: 120}
                        , {field: 'content',  title: '简介'}
                        , {
                        field: 'type',  title: '分类',width: 140, templet: function (data) {
                            return data.type.name
                        }
                    }
                        , {fixed: 'right', title: '操作', toolbar: '#barDemo', align:'center'}
                    ]
                ]
                , page: true
            });

            //处理下拉框数据
            makeSelect('add','search');
            // 执行搜索，表格重载
            $('#do_search').on('click', function () {
                // 搜索条件
                var send_name = $('#send_name').val();
                var send_price = $('#send_price').val();
                var send_type = $('#send_type').val();
                table.reload('test', {
                    method: 'get'
                    , where: {
                        'name': send_name,
                        'price': send_price,
                        'typeId': send_type
                    }
                    , page: {
                        curr: 1
                    }
                });
            })

            var submitUrl;
            var submitType;
            //弹出新增菜品弹出框
            function openAddDiv(){
                addDiv=layer.open({
                    type:1,
                    title:'添加',
                    area:['370px','440px'],
                    content:$('#insertOrUpdateDiv'),
                    success:function () {
                        //清空表单
                        $('#dataFrm')[0].reset();
                        //隐藏上传图片按钮
                        $('#editUploadBtn').attr('style','display:none')
                        $('#picture').val('');
                        $('#demo1').attr('src','');
                        $('#demo1').attr('style','display: none');

                        //处理下拉框数据
                        makeSelect('add','insertOrUpdate');
                        //添加请求url
                        submitUrl='/goodsApi/insertGoods';
                        submitType='POST';
                    }
                })
            }

            var currentId=-1;
            //弹出编辑菜品弹出框
            function openUpdateDiv(data){
                addDiv=layer.open({
                    type:1,
                    title:'编辑',
                    area:['370px','580px'],
                    content:$('#insertOrUpdateDiv'),
                    success:function () {
                        //初始化表单
                        form.val("dataFrm",data);
                        //隐藏上传图片按钮
                        $('#editUploadBtn').attr('style','display:none')
                        $('#demo1').attr('src', data.picture);
                        $('#demo1').attr('style','display: inline;border: 1px solid whitesmoke;');

                        //添加请求url
                        submitUrl='/goodsApi/updateGoodsById';
                        submitType='PUT';
                        //将当前表单的id属性存起来
                        currentId=data.typeId;
                        //处理下拉框数据
                        makeSelect('update','insertOrUpdate');
                    }
                })

            }

            //处理下拉框数据
            function makeSelect(type,a){

                $.get('/goodsApi/typeList',function (res) {

                    if (a==='search'){
                        var typeIds=$('#send_type')
                    }else if (a==='insertOrUpdate'){
                        var typeIds=$('#typeIds')
                    }

                    var typeInfo=res.data[0];
                    console.log("res："+res);

                    //遍历前先清空
                    typeIds.empty();
                    typeIds.append("<option value=''>"+'选择或搜索'+"</option>");
                    //遍历所有分类，渲染下拉框
                    $(typeInfo).each(function (index,element) {
                        // alert(element.id+"--"+element.name);

                        //如果当前分类的id==正在遍历的分类id，就给下拉增加selected属性
                        if(currentId!=-1&&type!='add'){

                            if(currentId==element.id){
                                typeIds.append("<option selected='selected' value="+element.id+">"+element.name+"</option>");
                            }else{
                                typeIds.append("<option value="+element.id+">"+element.name+"</option>");
                            }

                        }else{
                            typeIds.append("<option value="+element.id+">"+element.name+"</option>");
                        }

                        console.log("下拉列表---------"+typeInfo);
                        form.render('select');
                    })
                    // alert(tids.html())

                })
            }

            //头工具栏事件
            table.on('toolbar(test)', function(obj){
                var checkStatus = table.checkStatus(obj.config.id);
                var data = checkStatus.data;
                switch(obj.event){
                    case 'insert':
                        //弹出新增菜品弹出框
                        openAddDiv();
                        break;

                    case 'batchDelete':
                        if (data.length>0){
                            var ids='';
                            $.each(data,function (index) {
                                ids+=data[index].id+',';
                            })
                            ids=ids.substring(0,ids.length-1);
                            console.log(ids)
                            layer.confirm('真的删除所选么', function(index){
                                layer.close();

                                //向服务端发送删除指令
                                $.ajax({
                                    type: 'DELETE',
                                    data: {ids:ids},
                                    url: '/goodsApi/deleteGoodsById',
                                    success:function (res) {
                                        layer.msg(res.data);
                                        //刷新数据 表格
                                        tableIns.reload();
                                    }
                                })
                            });
                        }else{
                            layer.msg('至少选中一条数据')
                        }
                        break;
                };
            });

            //监听行工具事件
            table.on('tool(test)', function (obj) {
                var data = obj.data;
                if (obj.event === 'update') {
                    //弹出编辑商品弹出框
                    openUpdateDiv(data);
                }
                if (obj.event === 'delete') {
                    layer.confirm('真的删除【'+data.name+'】么', function(index){
                        obj.del(); //删除对应行（tr）的DOM结构
                        layer.close();
                        //向服务端发送删除指令
                        $.ajax({
                            type: 'DELETE',
                            data:  {ids:data.id},
                            url: '/goodsApi/deleteGoodsById',
                            success:function (res) {
                                layer.msg(res.data);
                            }
                        })
                    });
                }
            });

            //普通图片上传
            var uploadInst = upload.render({
                elem: '#test1'
                ,url: '/uploadApi/upload/1' //改成您自己的上传接口
                ,auto: false
                ,size: 1024 //限制文件大小，单位 KB
                ,accept: 'images'   //文件类型
                ,acceptMime: 'image/*'
                ,field: 'uploadFile'
                // ,bindAction: '#uploadBtn'//绑定上传按钮
                , choose: function (obj) {
                    //选完图片后
                    obj.preview(function (index, file, result) {
                        //显示上传图片按钮
                        $('#editUploadBtn').attr('style','display:inline')
                        //选图片就将#picture的输入框清空
                        $('#picture').val('');
                        //显示预览图片
                        $('#demo1').attr('style','display: inline;border: 1px solid whitesmoke;');
                        $('#demo1').attr('src', result); //图片链接（base64）
                    });
                }
                , done: function (res) {
                    //关闭加载层
                    layer.closeAll('loading');
                    if (res.code >0) {
                        return layer.msg(res.data);
                    }else{
                        layer.alert('上传成功');
                        //将服务器存放的图片路径设置在#picture的输入框
                        $('#picture').val(res.data.src);
                    }
                    //上传成功
                }
                , error: function () {
                    //关闭加载层
                    layer.closeAll('loading');
                    //演示失败状态，并实现重传
                    var demoText = $('#demoText');
                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                    demoText.find('.demo-reload').on('click', function () {
                        uploadInst.upload();
                    });
                }
            });

            //自定义绑定上传按钮
            $('#uploadBtn').click(function () {

                if ($('#demo1').attr('src')!=''){
                    //加载层
                    layer.load(2);
                    uploadInst.upload();
                }else{
                    layer.msg('你还没选择图片')
                }

            })

            form.verify({
                name: [/^[\u4e00-\u9fa5]{0,10}$/, '必须是长度1~10的中文'],
                price: [/^(-?\d+)(\.\d+)?$/, '必须是数字'],
                content: function(value){
                    if(value.length >40 ){
                        return "长度不能超过40";
                    }
                },
                picture: function(value){
                    if(value.length == 0){
                        return "请先上传图片";
                    }
                }
            })

            //提交
            form.on("submit(submit)",function (obj) {
                //序列化表单数据
                var params=$("#dataFrm").serialize();
                //请求后端添加或编辑方法
                $.ajax({
                    type:submitType,
                    url:submitUrl,
                    data:params,
                    success:function (data) {
                        if(data.code===200){
                            layer.msg(data.data)
                        }else{
                            layer.alert('服务器异常', {icon: 2});
                        }

                        //关闭弹出层
                        layer.close(addDiv)
                        //刷新数据 表格
                        tableIns.reload();
                    }
                })

            })

            // 表格格式化  -  img 渲染
            function img(cellvalue) {
                console.log(cellvalue);
                return "<img src='" + cellvalue.picture + "' height=\"90\" width=\"100\" />";
            }
        });
    </script>

</div>
</body>
</html>